Telegram Group & Telegram Channel
🐍 Python-задача с подвохом: “Список-призрак”

📘 Условие

Посмотри на этот код:


def append_item(item, lst=[]):
lst.append(item)
return lst

result1 = append_item(1)
result2 = append_item(2)
result3 = append_item(3)

print(result1)
print(result2)
print(result3)


Вопрос:
Что выведет программа и почему?

🔍 Варианты ответа:

А)

[1]
[2]
[3]


Б)

[1]
[1, 2]
[1, 2, 3]


В)

[3]
[3]
[3]


Правильный ответ: Б

Почему?

💥 Подвох: аргумент lst=[] — мутабельный объект, и он создаётся только один раз при определении функции, а не при каждом вызове.

📌 То есть каждый вызов append_item модифицирует один и тот же список, который "помнит" все предыдущие элементы.

Как исправить:


def append_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst


Теперь каждый вызов создаёт новый список, если его не передали явно.

⚠️ Подвох

• Аргументы по умолчанию вычисляются один раз
• Это работает и с dict, и с set, и с любыми объектами
• Даже опытные Python-разработчики иногда "попадаются" на этом

🎯 Отлично подходит для проверки глубокого понимания поведения функций в Python.



tg-me.com/pro_python_code/1804
Create:
Last Update:

🐍 Python-задача с подвохом: “Список-призрак”

📘 Условие

Посмотри на этот код:


def append_item(item, lst=[]):
lst.append(item)
return lst

result1 = append_item(1)
result2 = append_item(2)
result3 = append_item(3)

print(result1)
print(result2)
print(result3)


Вопрос:
Что выведет программа и почему?

🔍 Варианты ответа:

А)

[1]
[2]
[3]


Б)

[1]
[1, 2]
[1, 2, 3]


В)

[3]
[3]
[3]


Правильный ответ: Б

Почему?

💥 Подвох: аргумент lst=[] — мутабельный объект, и он создаётся только один раз при определении функции, а не при каждом вызове.

📌 То есть каждый вызов append_item модифицирует один и тот же список, который "помнит" все предыдущие элементы.

Как исправить:


def append_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst


Теперь каждый вызов создаёт новый список, если его не передали явно.

⚠️ Подвох

• Аргументы по умолчанию вычисляются один раз
• Это работает и с dict, и с set, и с любыми объектами
• Даже опытные Python-разработчики иногда "попадаются" на этом

🎯 Отлично подходит для проверки глубокого понимания поведения функций в Python.

BY Python RU


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/pro_python_code/1804

View MORE
Open in Telegram


Python RU Telegram | DID YOU KNOW?

Date: |

How To Find Channels On Telegram?

There are multiple ways you can search for Telegram channels. One of the methods is really logical and you should all know it by now. We’re talking about using Telegram’s native search option. Make sure to download Telegram from the official website or update it to the latest version, using this link. Once you’ve installed Telegram, you can simply open the app and use the search bar. Tap on the magnifier icon and search for a channel that might interest you (e.g. Marvel comics). Even though this is the easiest method for searching Telegram channels, it isn’t the best one. This method is limited because it shows you only a couple of results per search.

China’s stock markets are some of the largest in the world, with total market capitalization reaching RMB 79 trillion (US$12.2 trillion) in 2020. China’s stock markets are seen as a crucial tool for driving economic growth, in particular for financing the country’s rapidly growing high-tech sectors.Although traditionally closed off to overseas investors, China’s financial markets have gradually been loosening restrictions over the past couple of decades. At the same time, reforms have sought to make it easier for Chinese companies to list on onshore stock exchanges, and new programs have been launched in attempts to lure some of China’s most coveted overseas-listed companies back to the country.

Python RU from cn


Telegram Python RU
FROM USA